import {defineStore} from 'pinia'
import {ref, computed} from 'vue'
import {getToken, removeToken} from '@/utils/auth'
import type {API} from "@/type/type";
import {getUserInfoAPI, logoutAPI} from "@/api/auth";
import {useRouter} from 'vue-router';
import type {ComputedRef, Ref} from 'vue'

interface AuthStore {
  currentUser: Ref<API.ICurrentUser | null>
  setCurrentUser: () => Promise<API.ICurrentUser | void>
  logout: () => Promise<void>
  hasRole: (role: string) => ComputedRef<boolean>
  isAuthenticated: ComputedRef<boolean>
  currentRoles: ComputedRef<string[]>
  currentPermissions: ComputedRef<string[]>
}


export const useAuthStore = defineStore('auth', (): AuthStore => {
  // 用户信息
  const currentUser = ref<API.ICurrentUser | null>(null)
  const router = useRouter()

  // 设置用户信息
  const setCurrentUser = async () => {
    if (!getToken()) {
      router.push('/login')
      return
    }
    const {data} = await getUserInfoAPI()
    currentUser.value = data
  }

  // 登出
  const logout = async () => {
    currentUser.value = null
    await logoutAPI()
    removeToken()
    router.push('/login')
  }

  // 检查是否有特定角色
  const hasRole = (role: string) => computed(() => {
    return currentUser.value?.roles.includes(role) || false
  })

  // 检查是否已登录
  const isAuthenticated = computed(() => !!currentUser.value)

  // 获取当前用户角色
  const currentRoles = computed(() => currentUser.value?.roles || [])
  // 获取当前权限
  const currentPermissions = computed(() => currentUser.value?.permissions || [])

  return {
    currentUser,
    setCurrentUser,
    logout,
    hasRole,
    isAuthenticated,
    currentRoles,
    currentPermissions
  }
})
